'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: cos_service.py
* @Time: 2025/11/12
* @All Rights Reserve By Brtc
'''
import hashlib
import os
import uuid
from dataclasses import dataclass
from datetime import datetime

from injector import inject
from qcloud_cos import CosConfig, CosS3Client
from werkzeug.datastructures import FileStorage

from internal.entity.upload_file_entity import ALLOWED_IMAGE_EXTENSION, ALLOWED_FILE_EXTENSION
from internal.exception.exception import FailException
from internal.model import UploadFile


from .upload_file_service import UploadFileService



@inject
@dataclass
class CosService:
    """腾讯云对象存储服务"""
    upload_file_service: UploadFileService

    def upload_file(self, file:FileStorage, only_image:bool=False)->UploadFile:
        """上传文件到腾讯云cos 对象存储， 上传后返回文件的信息"""
        # todo:等待授权认证模块完成进行切换调整
        account_id = "e036e651-9eae-4b15-8dc3-b9d692121acf"
        #1、提取文件扩展名，并检测是否可以上传
        filename  = file.filename
        extension = file.filename.rsplit(".", 1)[-1] if "." in filename else ""
        if extension.lower() not in (ALLOWED_IMAGE_EXTENSION + ALLOWED_FILE_EXTENSION):
            raise FailException(f"该 {extension} 扩扩展的文件 不允许上传！！")
        elif only_image and extension not in ALLOWED_IMAGE_EXTENSION:
            raise FailException(f"该 {extension} 图片格式不支持上传， 请上传正确的图片！")
        #2、获取客户端 + 存储桶的名字
        client = self._get_client()
        bucket = self._get_bucket()

        #3、生成一个随机名字
        random_filename = str(uuid.uuid4()) + "." + extension
        now = datetime.now()
        upload_filename = f"{now.year}/{now.month:02d}/{now.day:02d}/{random_filename}"
        #4、流式读取上传的数据并将其上传到 cos 中
        file_content = file.stream.read()

        try:
            #5、将数据上传到cos中
            client.put_object(bucket, file_content,upload_filename)
        except Exception as e:
            raise FailException(f"上传文件失败: {e} !")
        #6、创建 upload file 记录
        return self.upload_file_service.create_upload_file(
            account_id=account_id,
            name=filename,
            key=upload_filename,
            size=len(file_content),
            extension=extension,
            mime_type=file.mimetype,
            hash=hashlib.sha3_256(file_content).hexdigest(),
        )


    def download_file(self, key:str, target_file_path:str):
        """下载cos 云端的文件到指定本地路径"""
        client = self._get_client()
        bucket = self._get_bucket()
        client.download_file(bucket, key, target_file_path)


    @classmethod
    def get_file_url(cls, key:str)->str:
        """根据传递的cos云端key获取图片实际的url 地址"""
        cos_domain = os.getenv("COS_DOMAIN")
        if not cos_domain:
            bucket = os.getenv("COS_BUCKET")
            scheme = os.getenv("COS_SCHEME")
            region = os.getenv("COS_REGION")
            cos_domain = f"{scheme}://{bucket}.cos.{region}.mycloud.com"
        return f"{cos_domain}/{key}"


    @classmethod
    def _get_client(cls):
        """获取腾讯云客户端"""
        conf = CosConfig(
            Region=os.getenv("COS_REGION"),
            SecretId=os.getenv("COS_SECRET_ID"),
            SecretKey=os.getenv("COS_SECRET_KEY"),
            Token=None,
            Scheme=os.getenv("COS_SCHEME", "https"),
        )
        return CosS3Client(conf)



    @classmethod
    def _get_bucket(cls):
        """获取存储桶名字"""
        return os.getenv("COS_BUCKET")






















